package com.liu.stockmarket.ui.datacenter.ui.newbond

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import com.liu.stockmarket.BaseFragment
import com.liu.stockmarket.R
import com.liu.stockmarket.StockMarketApplication
import com.liu.stockmarket.databinding.FragmentNewBondBinding
import com.liu.stockmarket.databinding.FragmentStockBinding
import com.liu.stockmarket.databinding.HeaderOrderItemBinding
import com.liu.stockmarket.databinding.HeaderStockSummaryBinding
import com.liu.stockmarket.model.NewBond
import com.liu.stockmarket.ui.datacenter.DataCenterViewModel
import com.liu.stockmarket.ui.datacenter.ui.main.PlaceholderFragment
import com.liu.stockmarket.utils.YMDParse
import com.liu.stockmarket.utils.onTabSelected
import com.liu.stockmarket.utils.toast
import java.lang.IllegalArgumentException
import java.time.LocalDate


/**
 * A simple [Fragment] subclass.
 * Use the [NewBondFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class NewBondFragment : BaseFragment() {

    private var param1: String? = null
    private var param2: String? = null

    private lateinit var viewModel: DataCenterViewModel

    private var _binding: FragmentNewBondBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    private lateinit var mAdapter: NewBondAdapter

    private  val bonds = mutableListOf<NewBond>()

    private var pageNumber = 1;


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }


    override fun initView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        _binding = FragmentNewBondBinding.inflate(inflater, container, false)
        val root: View = binding.root
        val application = this.requireActivity().application as StockMarketApplication
        viewModel = ViewModelProvider(
            this,
            DataCenterViewModel.DataCenterViewModelFactory(application.easyMoneyRepository)
        ).get(DataCenterViewModel::class.java)

        mAdapter = NewBondAdapter()

        binding.list.adapter = mAdapter

        mAdapter.loadMoreModule.isEnableLoadMoreIfNotFullPage = true
        mAdapter.loadMoreModule.loadMoreToLoading()


        return root
    }

    private fun loadData(pageNumber: Int) {
        viewModel.getNewBond(pageNumber = pageNumber)
    }

    override fun listener() {
        binding.tabs.onTabSelected { it ->

            when (it.position) {
                0 -> {
                    mAdapter.setList(bonds)
                }
                1 -> {
                    // 即将申购
                    val localBonds = bonds
                    mAdapter.setList(localBonds.filter { b ->
                        !b.PUBLIC_START_DATE.substring(0, 10).YMDParse().isBefore(LocalDate.now())
                    }.sortedBy { b-> b.PUBLIC_START_DATE })

                    mAdapter.loadMoreModule.isEnableLoadMore = false
                }
                2 -> {
                    // 即将上市
                    val localBonds = bonds
                    mAdapter.setList(localBonds.filter { b ->
                        b.LISTING_DATE != null && !b.LISTING_DATE.substring(0, 10).YMDParse()
                            .isBefore(LocalDate.now())
                    }.sortedBy { b-> b.LISTING_DATE })
                    mAdapter.loadMoreModule.isEnableLoadMore = false
                }
                3 -> {
                    // 等待上市
                    val localBonds = bonds
                    mAdapter.setList(localBonds.filter { b ->
                        b.LISTING_DATE == null && b.PUBLIC_START_DATE.substring(0, 10).YMDParse()
                            .isBefore(LocalDate.now())
                    })
                    mAdapter.loadMoreModule.isEnableLoadMore = false

                }
                else -> {
                    throw  IllegalArgumentException("我没有这么大")
                }
            }
        }
        mAdapter.loadMoreModule.setOnLoadMoreListener {
           loadData(pageNumber++)
        }
    }

    override fun observer() {
        viewModel.bonds.observe(this) {
            bonds.addAll(it)
            mAdapter.setList(bonds)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }

    companion object {
        // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
        private const val ARG_PARAM1 = "param1"
        private const val ARG_PARAM2 = "param2"

        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment NewBondFragment.
         */

        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            NewBondFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }
}